package com.tuniu.agents.common.message;

import com.tuniu.agents.memory.MemoryManager;
import com.tuniu.agents.message.MessageMemoryManager;
import com.tuniu.agents.message.MessageSender;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MessageMemorySenderManager implements MessageMemoryManager {

    protected final MemoryManager memoryManager;

    protected final MessageSender messageSender;

    public MessageMemorySenderManager(MemoryManager memoryManager, MessageSender messageSender) {
        this.memoryManager = memoryManager;
        this.messageSender = messageSender;
    }


    /**
     * Insert context and send return stream
     * @param conversationId the ID of the conversation
     * @param message the message to send
     * @param agentId the ID of the agent
     * @param memory the memory list to be used
     */
    @Override
    public void send(String conversationId, String message, String agentId, List<String> memory) {
        if(!StringUtils.hasText(conversationId)){
            return;
        }
        if(!StringUtils.hasText(message)){
            message = "No information was found for the current query, please try a different question.";
        }
        // Submit to the stream for returning information
        messageSender.send(conversationId,BaseAgentNewResp.sendAnswerMsg(null,message));
        if(StringUtils.hasText(agentId) && !CollectionUtils.isEmpty(memory)){
            // Submit to the context
            List<Message> memorys = new ArrayList<>();
            memory.forEach(m -> memorys.add(new AssistantMessage(m, Map.of("agentId",agentId))));
            memoryManager.setMessageRight(conversationId,memorys);
        }
    }

}
